/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.service;

import com.ivanbiz.dao.BankDAO;
import com.ivanbiz.dao.impl.BankDAOImpl;
import com.ivanbiz.model.Bank;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

/**
 *
 * @author iw20149x
 */
public class BankService1 extends SelectorComposer<Component> {

    BankDAO bankDAO = new BankDAOImpl();
    List<Bank> loadBank;
    @Wire
    Listbox listBank;
    @Wire
    Textbox nama;
    @Wire
    Textbox deskripsi;
    @Wire
    Window win;

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        loadBank = bankDAO.getAll(Bank.class);
        loadBank();
    }

    private void loadBank() {
        int no = 0;
        int x = 0;
        for (Bank bank : loadBank) {
            no += 1;
            Listitem item = new Listitem();
            item.setValue(bank);
            item.appendChild(new Listcell(String.valueOf(no)));
            item.appendChild(new Listcell(bank.getNama()));
            item.appendChild(new Listcell(bank.getDeskripsi()));
            listBank.appendChild(item);
            ++x;
        }
    }

    @Listen("onClick=#tambah;")
    public void tambah() {
        try {
            System.out.println("masuk");
            Window wins = (Window) Executions.createComponents("/bank_add.zul", null, null);
            wins.doModal();
            System.out.println("belum");
            wins.doEmbedded();
            System.out.println("belum");
            loadBank = bankDAO.getAll(Bank.class);
            loadBank();
        } catch (Exception ex) {
            Logger.getLogger(BankService1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onClick=#simpan;")
    public void simpan() {
        Bank bank = new Bank();
        bank.setNama(nama.getValue());
        bank.setDeskripsi(deskripsi.getValue());
        validate(bank);
    }

    private void validate(Bank bank) {
        if (bank == null) {
            Messagebox.show("Bank tidak boleh kosong");
        } else if (bank.getNama().isEmpty()) {
            Messagebox.show("Nama tidak boleh kosong");
        } else {
            try {
                bankDAO.save(bank);
                win.detach();
            } catch (Exception ex) {
                Logger.getLogger(BankService1.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}
